package pri.damai.xiaowu.gateway.security.handle;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import pri.damai.xiaowu.common.core.enums.ResultCommonEnum;
import pri.damai.xiaowu.common.core.vo.ResultVO;
import pri.damai.xiaowu.gateway.enums.GatewayResultEnum;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 *
 * @Desc
 * @Author DaMai
 * @Date 2021/4/28 14:40
 * 但行好事，莫问前程。
 */
@Component
public class XiaoWuAccessDeniedHandler implements ServerAccessDeniedHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        return Mono
                .defer(() -> Mono.just(exchange.getResponse()))
                .flatMap(response -> {

                    response.setStatusCode(HttpStatus.OK);
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    response.getHeaders().setAccessControlAllowOrigin("*");
                    DataBufferFactory dataBufferFactory = response.bufferFactory();

                    String result = JSONObject.toJSONString(ResultVO.error(GatewayResultEnum.PERMISSION_DENIED));
                    DataBuffer buffer = dataBufferFactory.wrap(result.getBytes(
                            Charset.defaultCharset()));
                    return response.writeWith(Mono.just(buffer));
                });

    }
}
